package com.visual.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WifiP2pActivity extends AppCompatActivity {

    TextView logTextView;
    private WifiP2pManager manager;
    private final IntentFilter intentFilter = new IntentFilter();
    private WifiP2pManager.Channel channel;
    private boolean isWifiP2pEnabled = false;
    WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peers) {
            logTextView.append(StrUtils.formatMsg("onPeersAvailable()", peers.toString()));
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
                int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
                if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                    logTextView.append(StrUtils.formatMsg("onReceive()", "WifiP2pManager.WIFI_P2P_STATE_ENABLED"));
                    isWifiP2pEnabled = true;
                    discoverPeers();
                } else {
                    logTextView.append(StrUtils.formatMsg("onReceive()", "WifiP2pManager.WIFI_P2P_STATE_DISABLED"));
                    isWifiP2pEnabled = false;
                }
            } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
                    logTextView.append(StrUtils.formatMsg("onReceive()", "WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION"));
                    manager.requestPeers(channel, peerListListener);
            } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
                logTextView.append(StrUtils.formatMsg("onReceive()", "WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION"));
                NetworkInfo networkInfo = (NetworkInfo) intent
                        .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
                if (networkInfo.isConnected()) {
                    logTextView.append(StrUtils.formatMsg("isConnected()", "true"));
//                    DeviceDetailFragment fragment = (DeviceDetailFragment) activity
//                            .getFragmentManager().findFragmentById(R.id.frag_detail);
//                    manager.requestConnectionInfo(channel, fragment);
                } else {
                    logTextView.append(StrUtils.formatMsg("isConnected()", "false"));
                }
            } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
                logTextView.append(StrUtils.formatMsg("onReceive()", "WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION"));
//                DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
//                        .findFragmentById(R.id.frag_list);
//                fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
//                        WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));

            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logTextView = (TextView) findViewById(R.id.tv_log_output);
        initWifiP2p();
    }

    @Override
    protected void onResume() {
        super.onResume();
        logTextView.setText("下面为调试输出：");
        StrUtils.resetMsgIndex();
        //discoverPeers();
    }

    private void initWifiP2p() {
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

        manager = (WifiP2pManager) getSystemService(this.WIFI_P2P_SERVICE);
        channel = manager.initialize(this, getMainLooper(), null);
        registerReceiver(receiver, intentFilter);
    }

    private void discoverPeers() {
        if (!isWifiP2pEnabled) {
            logTextView.append(StrUtils.formatMsg("discoverPeers()", "isWifiP2pEnabled is false"));
            return;
        }

        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                logTextView.append(StrUtils.formatMsg("discoverPeers()", "Discovery Initiated"));
            }

            @Override
            public void onFailure(int reasonCode) {
                logTextView.append(StrUtils.formatMsg("discoverPeers()", "Discovery Failed"));
            }
        });
    }
}
